const crypto = require('crypto');
const X2JS = require('x2js');

function sign(params, key) {
    let keys = Object.keys(params).sort();
    let str = [...keys.map(k => `${k}=${params[k]}`), `key=${key}`].join('&');
    return crypto.createHash('md5').update(str).digest('hex').toUpperCase();
}

function getSignedXml(params, key) {
    let copy = Object.assign({}, params);
    copy.sign = sign(params, key);
    let x2js = new X2JS();
    return `<xml>${x2js.js2xml(copy)}</xml>`;
}

module.exports = {
    sign,
    getSignedXml
};